//
//  ProvinceViewController.m
//  I_LiaoNing
//
//  Created by 王心磊 on 15-4-9.
//  Copyright (c) 2015年 王心磊. All rights reserved.
//

#import "ProvinceViewController.h"

@interface ProvinceViewController ()

@end

@implementation ProvinceViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [GiFHUD dismiss];
    self.navigationItem.title = @"大爱中国";
   self.tableView= [[UITableView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    [self.view addSubview:self.tableView];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView release];
    self.tableView.separatorStyle= NO;
    
    self.allProvinceArray = [NSMutableArray array];
     self.page = 1;
    [self addHeader];
    [self addFooter];
   [GiFHUD setGifWithImageName:@"20090724180330510251.gif"];
    
    
    // Do any additional setup after `loading the view.
}

#pragma mark --下拉刷新
- (void)addHeader
{
    //    __unsafe_unretained typeof(self) vc = self;
    __block ProvinceViewController *ProVc = self;
    
    // 添加下拉刷新头部控件
    [self.tableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        //在block块里实现afn数据请求,一定要写在这里
        [ProVc getAFNData:0];
        
        ProVc.isUpLoading = NO;
        NSLog(@"下拉刷新，开始网络请求第一页数据");
        
    }];
#pragma mark  --自动刷新(一进入程序就下拉刷新)
        [self.tableView headerBeginRefreshing];
    }


#pragma mark --上拉加载更多
- (void)addFooter
    {
        //    __unsafe_unretained typeof(self) vc = self;
        __block ProvinceViewController *vc = self;
        
        // 添加上拉刷新尾部控件
        [self.tableView addFooterWithCallback:^{
            // 进入刷新状态就会回调这个Block
            vc.isUpLoading = YES;
            NSLog(@"上拉加载更多，开始网络请求更多数据");
            
            
            //用afn加载更多的数据
            
            
            self.page++;
            [vc getAFNData:vc.page];
            
            
            
            
        }];
    }
#pragma AFN 请求数据
-(void)getAFNData:(NSInteger)page
{
    [GiFHUD show];
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    
    NSString *url_string = [NSString stringWithFormat:@"http://open.qyer.com/place/city/get_city_list?app_installtime=1428389862&client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&countryid=11&lat=38.88288716722717&lon=121.5399051889384&page=%ld",page];
    
    
    
    
    //[NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];  代表支持所有的接口类型
    
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
        NSLog(@"使用AFN进行get请求 ===  %@",responseObject);
        
        
        NSDictionary *dic = responseObject;
        NSMutableArray *array = [dic objectForKey:@"data"];
     
            
            // 打开数据库
            [[DataHandlePro shareDataBaseHandle]openDB];
            // 清除表
        if (_isUpLoading == NO) {
            
            [[DataHandlePro shareDataBaseHandle]dropTable];
            [[DataHandlePro shareDataBaseHandle ]createDB];
        }
        if (_isUpLoading == YES) {
            [[DataHandlePro shareDataBaseHandle]createDB];
        }
        for (NSDictionary *dic2  in array)
        {
            ProvinceModel *model = [[ProvinceModel alloc]init];
            [model setValuesForKeysWithDictionary:dic2];
            model.photo = [dic2 objectForKey:@"photo"];
            [self.allProvinceArray addObject:model];
            [[DataHandlePro shareDataBaseHandle]insertProvinceModel:model];
           
            
        }
        //让自动下拉刷新停止
        [self.tableView headerEndRefreshing];
        [self.tableView footerEndRefreshing];
        [GiFHUD dismiss];
        // 刷新tableView
        [self.tableView reloadData];
            
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [GiFHUD dismiss];
        NSLog(@"失败==== %@",error);
        
    }];

}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    [[DataHandlePro shareDataBaseHandle]openDB];
    NSMutableArray  *array = [[DataHandlePro shareDataBaseHandle]selectAllModel];
    return array.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifer = @"cell";
    ProvinceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer];
    if (cell == nil) {
        cell = [[ProvinceTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifer];
        
    }
    [[DataHandlePro shareDataBaseHandle]openDB];
   NSMutableArray *array =  [[DataHandlePro shareDataBaseHandle]selectAllModel];
    
    ProvinceModel *model = [array objectAtIndex:indexPath.row];
    
    cell.model = model;
    
    
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailsViewController *deVc = [[DetailsViewController alloc]init];
        [[DataHandlePro shareDataBaseHandle]openDB];
    NSMutableArray *array =  [[DataHandlePro shareDataBaseHandle]selectAllModel];
    ProvinceModel *model = [array objectAtIndex:indexPath.row];
    deVc.id = model.id;
    deVc.photo = model.photo;
    deVc.catename = model.catename;
    [self.navigationController pushViewController:deVc animated:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
